"use strict";

/**web服务器文件上传模块
 * @deprecated
 * */
function webServerFileUpdateModule(option) {

    console.warn("此模块不再升级维护！");

    /**工具库实例类*/
    let webServerFileUpdateModuleTools = this;

    let tempTools = webServerFileUpdateModuleTools.lightCopy(webServerFileUpdateModuleTools);

    tempTools.DataTypeDetect({
        _GlobalOperate: {
            enableDict: true, bind: {
                String: {aliasVal: "str", aliasDsc: "为字符串类型"},
                Array: {aliasVal: "arr", aliasDsc: "为数组类型"},
                Object: {aliasVal: "obj", aliasDsc: "为对象类型"},
                Boolean: {aliasVal: "boo", aliasDsc: "为布尔类型"},
                Number: {aliasVal: "num", aliasDsc: "为数字类型"},
                Undefined: {aliasVal: "und", aliasDsc: "未知定义类型"},
                Function: {aliasVal: "fun", aliasDsc: "为函数类型"},
                AsyncFunction: {aliasVal: "anf", aliasDsc: "为异步函数类型"},
                Null: {aliasVal: "nul", aliasDsc: "为空数据类型"},
                process: {aliasVal: "pro", aliasDsc: "Node JS Process对象"}
            }, RetValueType: 0
        }
    });

    let FinalBuilder = {
        _Kits: tempTools.lightCopy(tempTools),
        SaveLocation: "",
        AppendPrefix: "",
        AppendSuffix: "",
        currentReceiveSize: undefined,
        currentReceiveCompleteFile: undefined,
        ReceiverStatusConst: {
            NOT_RECEIVING: 0,
            RECEIVING: 1,
            RECEIVING_COMPLETE: 2
        },
        receiverStatus: 0,
        uploadFile(req, callback) {
            let Instance = this;
            let DataBuffer = [];
            let col = 0;
            Instance.receiverStatus = 0;

            /**文件流实例*/
            let StreamInstance;

            /**设置接收数据编码*/
            req.setEncoding('binary');

            /**文件数据块大小数据*/
            let FileSize = [];

            /**当前需要接收数据的文件名称*/
            let currentNeedReceiveFileName;

            req.on("data", function (value) {
                Instance.currentReceiveSize = 0;
                DataBuffer[col] = value;
                let EndSymbol;
                Instance.receiverStatus = 1;
                if (col === 0) {
                    let gd = Instance._Kits.findStringEx({
                        SourceStringData: DataBuffer[0],
                        FindKeyWord: "\r\n\r\n",
                        EnableStrictMode: true,
                        RetValueType: 1,
                        FindDirection: 0
                    });
                    /**获取文件原始信息*/
                    let receiverDataBlock = Instance._Kits.lightCopy(DataBuffer[col]);
                    let getFileInfo = Buffer.from(receiverDataBlock, 'binary').toString('utf-8');
                    let FileInfoHeaderLocation = Instance._Kits.findStringEx({
                        SourceStringData: getFileInfo,
                        FindKeyWord: "\r\n\r\n",
                        EnableStrictMode: true,
                        RetValueType: 1,
                        FindDirection: 0
                    });
                    let getFileName;
                    getFileName = Instance._Kits.lightCopy(String(getFileInfo).substr(0, parseInt(FileInfoHeaderLocation)));
                    getFileName = Instance._Kits.lightCopy(String(getFileName).split(`\r\n`)[1]);
                    getFileName = Instance._Kits.lightCopy(String(getFileName).split(`;`)[2]);
                    getFileName = Instance._Kits.lightCopy(String(getFileName).split(`="`)[1]);
                    getFileName = Instance._Kits.lightCopy(String(getFileName).substr(0, String(getFileName).length - 1));
                    if (getFileName === "" || Instance._Kits.findMultiEqualString(getFileName, " ", false, 0) === String(getFileName).length) {
                        return;
                    }
                    currentNeedReceiveFileName = (Instance.AppendPrefix + getFileName + Instance.AppendSuffix);
                    let FilePath = Instance._Kits.PathStream.join(Instance.SaveLocation, currentNeedReceiveFileName);
                    StreamInstance = Instance._Kits.FileStream.createWriteStream(FilePath, 'binary');
                    /**获取文件原始信息*/

                    let sc = String(DataBuffer[col]);
                    sc = String(sc.substr(parseInt(gd) + 4));
                    if (sc.length > 0) {
                        /**查找结束标记*/
                        EndSymbol = Instance._Kits.findStringEx({
                            SourceStringData: sc,
                            FindKeyWord: "\r\n-------",
                            EnableStrictMode: true,
                            RetValueType: 1,
                            FindDirection: 1
                        });
                        /**如果找到*/
                        if (EndSymbol !== undefined) {
                            let confirmData = sc.substr(0, parseInt(EndSymbol));
                            StreamInstance.write(confirmData, 'binary');
                            Instance.receiverStatus = 2;
                            FileSize[col] = confirmData.length;
                        } else {
                            StreamInstance.write(sc, 'binary');
                            FileSize[col] = sc.length;
                            col++;
                        }
                    }

                } else {
                    EndSymbol = Instance._Kits.findStringEx({
                        SourceStringData: DataBuffer[col],
                        FindKeyWord: "\r\n-------",
                        EnableStrictMode: true,
                        RetValueType: 1,
                        FindDirection: 1
                    });
                    if (EndSymbol !== undefined) {
                        let EndWriteBlock = DataBuffer[col].substr(0, parseInt(EndSymbol));
                        StreamInstance.write(EndWriteBlock, 'binary');
                        Instance.receiverStatus = 2;
                        FileSize[col] = EndWriteBlock.length;
                    } else {
                        StreamInstance.write(DataBuffer[col], 'binary');
                        FileSize[col] = DataBuffer[col].length;
                        col++;
                    }
                }
                Instance.currentReceiveSize = Instance._Kits.sum(...FileSize);
            });
            req.on("end", function () {
                if (Instance.receiverStatus === 2) {
                    Instance.currentReceiveCompleteFile = currentNeedReceiveFileName;
                    StreamInstance.close();
                }
                if (Instance._Kits.DataTypeDetect(callback) === 'fun' || Instance._Kits.DataTypeDetect(callback) === 'anf') {
                    callback(Instance.receiverStatus, currentNeedReceiveFileName);
                }
            })
        }
    };

    if (tempTools.DataTypeDetect(option) === 'obj' && tempTools.emptyObjectDetect(option) === false) {
        for (let chkBuildItem in option) {
            switch (chkBuildItem.toLowerCase()) {
                case "savelocation":
                    if (tempTools.FileStream.existsSync(option[chkBuildItem])) {
                        let chkDirInfo = tempTools.FileStream.statSync(option[chkBuildItem]);
                        if (chkDirInfo.isDirectory()) {
                            switch (process.platform) {
                                case "linux":
                                    if ((chkDirInfo.mode) >= 16877 && (chkDirInfo.mode) <= 20479) {
                                        FinalBuilder.SaveLocation = option[chkBuildItem];
                                    } else {
                                        throw new Error("SaveLocation属性指定的目录位置权限异常，无法正常使用！");
                                    }
                                    break;
                                case "win32":
                                    if ((chkDirInfo.mode) >= 16677 && (chkDirInfo.mode) <= 16822) {
                                        FinalBuilder.SaveLocation = option[chkBuildItem];
                                    } else {
                                        throw new Error("SaveLocation属性指定的目录位置权限异常，无法正常使用！");
                                    }
                                    break;
                            }
                        } else {
                            throw new Error("指定的路径不是目录！");
                        }
                    } else {
                        throw new Error("指定的存储路径不存在！");
                    }
                    break;
                case "appendprefix":
                    if (tempTools.DataTypeDetect(option[chkBuildItem]) === "num" || tempTools.DataTypeDetect(option[chkBuildItem]) === "str") {
                        FinalBuilder.AppendPrefix += option[chkBuildItem];
                    }
                    break;
                case "appendsuffix":
                    if (tempTools.DataTypeDetect(option[chkBuildItem]) === "num" || tempTools.DataTypeDetect(option[chkBuildItem]) === "str") {
                        FinalBuilder.AppendSuffix += option[chkBuildItem];
                    }
                    break;
                default:
                    throw new Error("出现未知的配置选项！");
            }
        }
    } else {
        throw new Error("没有构建参数对象！");
    }
    return FinalBuilder;
}

/**新式web服务器文件上传模块
 * */
function webServerDataUpdate(InterfaceRequest, option) {

    /**初始化部分变量*/
    let currentInstance = this.lightCopy(this);
    currentInstance.DataTypeDetect({
        _GlobalOperate: {
            enableDict: true, bind: {
                String: {aliasVal: "str", aliasDsc: "为字符串类型"},
                Array: {aliasVal: "arr", aliasDsc: "为数组类型"},
                Object: {aliasVal: "obj", aliasDsc: "为对象类型"},
                Boolean: {aliasVal: "boo", aliasDsc: "为布尔类型"},
                Number: {aliasVal: "num", aliasDsc: "为数字类型"},
                Undefined: {aliasVal: "und", aliasDsc: "未知定义类型"},
                Function: {aliasVal: "fun", aliasDsc: "为函数类型"},
                AsyncFunction: {aliasVal: "anf", aliasDsc: "为异步函数类型"},
                Null: {aliasVal: "nul", aliasDsc: "为空数据类型"},
                process: {aliasVal: "pro", aliasDsc: "Node JS Process对象"},
                Promise: {aliasVal: "pme", aliasDsc: "Node JS Promise对象"}
            }, RetValueType: 0
        }
    });

    /**静态保存路径*/
    let static_SavePath;

    /**正在接收的文件名称*/
    let running_FileName;

    /**获得确认回调后的数据*/
    let getConfirmCallBackData;

    /**保存位置回调函数*/
    let SavePathCallBack;
    /**保存文件名回调函数*/
    let FileNameCallBack;

    /**启用保存位置回调函数，false默认不启用*/
    let EnablePathCallback = false;
    /**启用文件名称回调函数，false默认不启用*/
    let EnableNameCallback = false;

    /**接收文件开始前事件函数*/
    let before_receive_event;
    /**接收文件进行中事件函数*/
    let running_receive_event;
    /**接收文件完成后事件函数*/
    let complete_receive_event;

    /**表单项分割符号*/
    let splitSymbol;
    /**表单结尾符号*/
    let FinalSplitSymbol;

    /**建立数据接收数组*/
    let ReceiveDataArray = [];

    /**文件数据存入流实例控制句柄组*/
    let StreamInstance = [];

    /**目录检测*/
    function dirDetect(path) {
        let detectValue = [];
        try {
            if (currentInstance.FileStream.existsSync(path) && currentInstance.FileStream.statSync(path).isDirectory()) {
                detectValue.push(true);
                let testDir = currentInstance.FileStream.statSync(path);
                switch (process.platform) {
                    case "linux":
                        if ((testDir.mode) < 16877 || (testDir.mode) > 20479) {
                            detectValue.push(false);
                        } else {
                            detectValue.push(true);
                        }
                        break;
                    case "win32":
                        if ((testDir.mode) < 16677 || (testDir.mode) > 16822) {
                            detectValue.push(false);
                        } else {
                            detectValue.push(true);
                        }
                        break;
                }
            } else {
                detectValue.push(false);
            }
        } catch (e) {
            detectValue.push(false);
        }
        return detectValue;
    }

    /**获取上传的文件信息*/
    function getFileInfo(Buff) {
        let FinFileInfo;
        if (typeof Buff === "string") {
            FinFileInfo = {
                Content_Disposition: "",
                Content_Type: "",
                FileName: "",
                Name: ""
            };
            let RawFileInfoPosition = currentInstance.findStringEx({
                SourceStringData: Buff,
                FindKeyWord: "\r\n\r\n",
                EnableStrictMode: true,
                RetValueType: 1,
                FindDirection: 0
            });
            let convertUTF8data = Buffer.from(String(Buff).substr(0, RawFileInfoPosition), 'binary').toString('utf-8');
            let dataSplitArr = String(convertUTF8data).split(`\r\n`);
            dataSplitArr.forEach((value, index, array) => {
                if (String(value).toString() === "") {
                    array.splice(index, 1);
                }
            });
            dataSplitArr.forEach((value, index, array) => {
                if (String(value).indexOf(`; `) >= 0) {
                    array.push(...String(value).split(`; `));
                    array.splice(index, 1);
                }
            });
            dataSplitArr.forEach((value, index, array) => {
                if (String(value).indexOf(`; `) >= 0) {
                    array.splice(index, 1);
                }
            });
            dataSplitArr.forEach((value, index, array) => {
                if (String(value).indexOf(': ') > 0) {
                    let sp1 = String(value).split(': ');
                    switch (String(sp1[0]).toLowerCase()) {
                        case"content-type":
                            FinFileInfo.Content_Type = currentInstance.lightCopy(sp1[1]);
                            break;
                        case"content-disposition":
                            FinFileInfo.Content_Disposition = currentInstance.lightCopy(sp1[1]);
                            break;
                        default:
                            break;
                    }
                } else if (String(value).indexOf('=') > 0) {
                    let sp2 = String(value).split('=');
                    let tmpval;
                    switch (String(sp2[0]).toLowerCase()) {
                        case "name":
                            tmpval = currentInstance.lightCopy(sp2[1]);
                            if (String(tmpval).charAt(0) === `"` && String(tmpval).charAt(tmpval.length - 1) === `"`) {
                                FinFileInfo.Name = String(tmpval).substring(1, (tmpval.length - 1));
                            } else {
                                FinFileInfo.Name = tmpval;
                            }
                            break;
                        case "filename":
                            tmpval = currentInstance.lightCopy(sp2[1]);
                            if (String(tmpval).charAt(0) === `"` && String(tmpval).charAt(tmpval.length - 1) === `"`) {
                                FinFileInfo.FileName = String(tmpval).substring(1, (tmpval.length - 1));
                            } else {
                                FinFileInfo.FileName = tmpval;
                            }
                            break;
                        default:
                            break;
                    }
                }
            });
        } else {
            throw new Error("收到的Buffer不是字符串！");
        }
        return FinFileInfo;
    }

    /**小型数据提取器*/
    function LittleDataExtract(BuffSource) {
        let getData;
        let data_start_pos = currentInstance.findStringEx({
            SourceStringData: BuffSource,
            FindKeyWord: "\r\n\r\n",
            EnableStrictMode: true,
            RetValueType: 1,
            FindDirection: 0
        });
        let data_end_pos = currentInstance.findStringEx({
            SourceStringData: BuffSource,
            FindKeyWord: "\r\n",
            EnableStrictMode: true,
            RetValueType: 1,
            FindDirection: 1
        });

        getData = String(BuffSource).toString().substr((data_start_pos + 4));

        if (String(getData).substr(getData.length - 2) === "\r\n") {
            return String(BuffSource).toString().substr((data_start_pos + 4), (data_end_pos - (data_start_pos + 4)));
        } else {
            return getData;
        }
    }

    /**大型数据提取器*/
    function LargeDataExtract(dataSource, dataSplit, dataEndSplit) {
        let FinalExtractData;
        let ExistSplitPos;
        let ExistSplitPosNum;
        let ExistEndSplitPos;
        let ExistEndSplitPosNum;
        let stpos;
        let enpos;

        function reSearch() {
            ExistSplitPos = currentInstance.findStringEx({
                SourceStringData: dataSource,
                FindKeyWord: dataSplit,
                EnableStrictMode: true,
                FindDirection: 0,
                RetValueType: 1
            });
            ExistSplitPosNum = currentInstance.findMultiEqualString(dataSource, dataSplit, true, 0, 0);
            ExistEndSplitPos = currentInstance.findStringEx({
                SourceStringData: dataSource,
                FindKeyWord: dataEndSplit,
                EnableStrictMode: true,
                FindDirection: 1,
                RetValueType: 1
            });
            ExistEndSplitPosNum = currentInstance.findMultiEqualString(dataSource, dataEndSplit, true, 0, 1);
        }

        reSearch();
        if (ExistSplitPos === undefined && ExistEndSplitPos === undefined) {
            FinalExtractData = currentInstance.lightCopy(dataSource);
        } else if (ExistSplitPosNum === 1 && ExistEndSplitPos === undefined) {
            if (ExistSplitPos === 0) {
                stpos = currentInstance.findStringEx({
                    SourceStringData: dataSource,
                    FindKeyWord: "\r\n\r\n",
                    EnableStrictMode: true,
                    RetValueType: 1,
                    FindDirection: 0
                });
                FinalExtractData = String(dataSource).substr(stpos + 4);
            } else {
                FinalExtractData = [];
                FinalExtractData[0] = String(dataSource).substr(0, ExistSplitPos);
                FinalExtractData[1] = String(dataSource).substr(ExistSplitPos);
            }
        } else if (ExistSplitPosNum > 1) {
            FinalExtractData = String(dataSource).split(dataSplit);
        } else if (ExistSplitPos === undefined && ExistEndSplitPosNum > 0) {
            FinalExtractData = String(dataSource).substr(0, (ExistEndSplitPos - 2));
        } else if (ExistSplitPos === 0 && ExistEndSplitPos >= 0) {
            stpos = currentInstance.findStringEx({
                SourceStringData: dataSource,
                FindKeyWord: "\r\n\r\n",
                EnableStrictMode: true,
                RetValueType: 1,
                FindDirection: 0
            });
            enpos = currentInstance.findStringEx({
                SourceStringData: dataSource,
                FindKeyWord: ("\r\n" + dataEndSplit),
                EnableStrictMode: true,
                RetValueType: 1,
                FindDirection: 1
            });
            FinalExtractData = String(dataSource).substr((stpos + 4), ((enpos - stpos) - 4));
        } else {
            if (ExistSplitPos === ExistEndSplitPos) {
                FinalExtractData = String(dataSource).substr(0, (ExistEndSplitPos - 2));
            } else {
                FinalExtractData = [];
                FinalExtractData[0] = String(dataSource).substr(0, (ExistSplitPos - 2));
                FinalExtractData[1] = String(dataSource).substr(ExistSplitPos, (ExistEndSplitPos - 2));
            }
        }
        if (typeof FinalExtractData === "object") {
            FinalExtractData.forEach((value, index, array) => {
                if (value === "") {
                    FinalExtractData.splice(index, 1);
                }
            });
        }
        return FinalExtractData;
    }

    /**保存路径、文件名称函数调用器*/
    async function SavePathFileNameCall(infoHeader) {

        if (Object.prototype.toString.call(infoHeader) !== "[object Object]") {
            throw new Error("infoHeader不是对象！");
        }

        /**最终拼合的全路径*/
        let FinalConfirm;

        /**最终获得的保存路径*/
        let confirmPath;

        /**最终获得的文件名称*/
        let confirmName;

        /**获取SaveLocation属性调用后的保存路径*/
        function getSavePath(path) {
            if (dirDetect(path)[0]) {
                if (dirDetect(path[1])) {
                    confirmPath = path;
                } else {
                    throw new Error("指定的目录位置权限异常！");
                }
            } else {
                throw new Error("指定的位置不是目录！");
            }
        }

        /**获取FileName属性调用后的文件名*/
        function getFileName(FileName) {
            confirmName = String(FileName).toString();
        }

        /**保存路径Promise等待实例*/
        let SavePathInstance;

        /**文件名称Promise等待实例*/
        let FileNameInstance;

        let s1 = false;
        let s2 = false;

        SavePathInstance = new Promise((resolve, reject) => {
            if (EnablePathCallback) {
                SavePathCallBack(resolve);
            } else {
                resolve(static_SavePath);
            }
        });
        FileNameInstance = new Promise((resolve, reject) => {
            if (EnableNameCallback) {
                FileNameCallBack(infoHeader, resolve);
            } else {
                resolve(infoHeader.FileName);
            }
        });

        await SavePathInstance.then((val1) => {
            getSavePath(val1);
            s1 = true;
        });
        await FileNameInstance.then((val2) => {
            getFileName(val2);
            s2 = true;
        });
        if (confirmName === undefined || confirmPath === undefined) {
            throw new Error("数据异常！");
        }

        if (s1 && s2) {
            FinalConfirm = [confirmPath, confirmName];
        } else if (!s1 && s2) {
            throw new Error("获取保存路径超时！");
        } else if (s1 && !s2) {
            throw new Error("获取文件名称超时");
        } else {
            throw new Error("回调异常！");
        }
        return FinalConfirm;
    }

    /**中间件检测机制*/
    if (currentInstance.DataTypeDetect(InterfaceRequest) === "obj" && currentInstance.emptyObjectDetect(InterfaceRequest) === false) {
        let {query, body, params, httpVersion, headers, rawTrailers, client, originalUrl} = InterfaceRequest;
        let tempChk = {
            query, body, params, httpVersion, headers, rawTrailers, client, originalUrl
        }
        for (let chkItem in tempChk) {
            if (tempChk[chkItem] === undefined) {
                throw new Error("不是合法的中间件客户端请求对象！");
            }
        }
    } else {
        throw new Error("InterfaceRequest没有收到中间件传递过来的客户端请求对象！");
    }

    if (currentInstance.DataTypeDetect(option) === "obj" && currentInstance.emptyObjectDetect(option) === false) {

        /**获取传递的参数对象*/
        for (let initOption in option) {
            switch (initOption.toLowerCase()) {
                case "savelocation":
                    switch (typeof option[initOption]) {
                        case "string":
                            if (currentInstance.FileStream.existsSync(option[initOption])
                                &&
                                currentInstance.FileStream.statSync(option[initOption]).isDirectory()
                            ) {
                                static_SavePath = currentInstance.lightCopy(option[initOption]);
                                EnablePathCallback = false;
                            } else {
                                throw new Error("SaveLocation属性指定的存储路径不是目录！");
                            }
                            break;
                        case "function":
                            SavePathCallBack = option[initOption];
                            EnablePathCallback = true;
                            break;
                        default:
                            throw new Error("SaveLocation属性必须是存放文件地址路径字符串或函数");
                    }
                    break;
                case "filename":
                    switch (typeof option[initOption]) {
                        case "function":
                            FileNameCallBack = option[initOption];
                            EnableNameCallback = true;
                            break;
                        default:
                            throw new Error("FileName属性绑定的数据必须是函数！");
                    }
                    break;
                case "before_receive":
                    if (typeof option[initOption] === "function") {
                        before_receive_event = option[initOption];
                    } else {
                        throw new Error("before_receive属性指向不是函数！");
                    }
                    break;
                case "running_receive":
                    if (typeof option[initOption] === "function") {
                        running_receive_event = option[initOption];
                    } else {
                        throw new Error("running_receive属性指向不是函数！");
                    }
                    break;
                case "complete_receive":
                    if (typeof option[initOption] === "function") {
                        complete_receive_event = option[initOption];
                    } else {
                        throw new Error("complete_receive属性指向不是函数！")
                    }
                    break;
                default:
                    throw new Error("出现未知的配置属性！");
            }
        }

        /**表单接收激活*/
        let detectActive = false;

        /**设置等待15秒状态检测*/
        let detectRec = setTimeout(() => {
            if (!detectActive) {
                throw new Error("接收超时！未收到要传输的 FormData 表单！");
            } else {
                clearTimeout(detectRec);
            }
        }, 15000);

        /**接收器*/
        function DataReceive() {

            /**设置接收编码为二进制编码*/
            InterfaceRequest.setEncoding('binary');

            /**初始化数据接收数组指针位置*/
            let ReceiveDataPosition = 0;

            /**获得的文件信息头*/
            let infoHeader;

            let lastDetectPoint = 0;
            /**终止接收检测*/
            let detectChange = setInterval(() => {
                if (ReceiveDataPosition > lastDetectPoint) {
                    lastDetectPoint = ReceiveDataPosition;
                } else {
                    for (let num in StreamInstance) {
                        StreamInstance[num].close(() => {
                            currentInstance.rmData(StreamInstance[num].path);
                        });
                    }
                    clearInterval(detectChange);
                }
            }, 1000);

            InterfaceRequest.on("data", async (value) => {

                /**向数组存入传输的数据*/
                ReceiveDataArray[ReceiveDataPosition] = value;

                let extractData;

                /**获取间隔符号*/
                if (ReceiveDataPosition === 0) {
                    /**改变触发状态*/
                    detectActive = true;

                    /**间隔符结束位置*/
                    let splitSymPos = parseInt(currentInstance.findStringEx({
                        SourceStringData: String(ReceiveDataArray[ReceiveDataPosition]).toString(),
                        FindKeyWord: "\r\n",
                        EnableStrictMode: true,
                        RetValueType: 1,
                        FindDirection: 0
                    }));

                    /**获得间隔符*/
                    splitSymbol = String(ReceiveDataArray[ReceiveDataPosition]).substr(0, splitSymPos);

                    /**拼合出最后间隔符*/
                    FinalSplitSymbol = splitSymbol + "--";
                }

                /**检测分格符号数量*/
                let ExistSplitNum = currentInstance.findMultiEqualString(
                    Buffer.from(ReceiveDataArray[ReceiveDataPosition]).toString("utf-8"), String(splitSymbol).toString(), true, 0, 0);

                /**第一个分格符号的位置*/
                let firstPos = currentInstance.findStringEx({
                    SourceStringData: Buffer.from(ReceiveDataArray[ReceiveDataPosition]).toString("utf-8"),
                    FindKeyWord: String(splitSymbol).toString(),
                    EnableStrictMode: true,
                    FindDirection: 0,
                    RetValueType: 1
                });

                /**检测最终末尾结束符号标记*/
                let ExistFinalSymbol = currentInstance.findMultiEqualString(
                    Buffer.from(ReceiveDataArray[ReceiveDataPosition]).toString("utf-8"), String(FinalSplitSymbol).toString(), true, 0, 1);

                let tmps;

                if (ExistSplitNum === 1 && ExistFinalSymbol === 0) {
                    infoHeader = getFileInfo(ReceiveDataArray[ReceiveDataPosition]);
                    extractData = LargeDataExtract(ReceiveDataArray[ReceiveDataPosition], splitSymbol, FinalSplitSymbol);
                    if (firstPos > 0) {
                        if (String(extractData[0]).substr(String(extractData[0]).length - 2) === "\r\n") {
                            extractData[0] = String(extractData[0]).substr(0, String(extractData[0]).length - 2);
                        }
                        if (typeof running_receive_event === "function") {
                            running_receive_event(running_FileName, String(extractData[0]).length);
                        }
                        StreamInstance[StreamInstance.length - 1].write(extractData[0], "binary");
                        await SavePathFileNameCall(infoHeader).then((val) => {
                            getConfirmCallBackData = val;
                        }).catch(val => {
                            throw new Error(val)
                        });
                        running_FileName = getConfirmCallBackData[1];
                        tmps = LittleDataExtract(extractData[1]);
                        if (typeof running_receive_event === "function") {
                            running_receive_event(running_FileName, String(tmps).length);
                        }
                        StreamInstance[StreamInstance.length] = currentInstance.FileStream.createWriteStream(
                            currentInstance.PathStream.join(getConfirmCallBackData[0], getConfirmCallBackData[1]), 'binary');
                        StreamInstance[StreamInstance.length - 1].write(tmps, 'binary');
                    } else {
                        await SavePathFileNameCall(infoHeader).then((val) => {
                            getConfirmCallBackData = val;
                        }).catch(val => {
                            throw new Error(val)
                        });
                        running_FileName = getConfirmCallBackData[1];
                        if (typeof running_receive_event === "function") {
                            running_receive_event(running_FileName, String(extractData).length);
                        }
                        StreamInstance[StreamInstance.length] = currentInstance.FileStream.createWriteStream(
                            currentInstance.PathStream.join(getConfirmCallBackData[0], getConfirmCallBackData[1]), 'binary');
                        StreamInstance[StreamInstance.length - 1].write(extractData, 'binary');
                    }
                } else if (ExistSplitNum > 1 && ExistFinalSymbol === 0) {
                    extractData = LargeDataExtract(ReceiveDataArray[ReceiveDataPosition], splitSymbol, FinalSplitSymbol);
                    if (firstPos > 0) {
                        tmps = String(extractData[0]).substr(0, String(extractData[0]).length - 2);
                        if (typeof running_receive_event === "function") {
                            running_receive_event(running_FileName, String(tmps).length);
                        }
                        StreamInstance[StreamInstance.length - 1].write(tmps, 'binary');
                        extractData.shift();
                    }
                    for (let num in extractData) {
                        infoHeader = getFileInfo(extractData[num]);
                        tmps = LittleDataExtract(extractData[num]);
                        await SavePathFileNameCall(infoHeader).then((val) => {
                            getConfirmCallBackData = val;
                        }).catch(val => {
                            throw new Error(val)
                        });
                        running_FileName = getConfirmCallBackData[1];
                        if (typeof running_receive_event === "function") {
                            running_receive_event(running_FileName, String(tmps).length);
                        }
                        StreamInstance[StreamInstance.length] = currentInstance.FileStream.createWriteStream(
                            currentInstance.PathStream.join(getConfirmCallBackData[0], getConfirmCallBackData[1]), 'binary');
                        StreamInstance[StreamInstance.length - 1].write(tmps, 'binary');
                    }
                } else if (ExistSplitNum > 1 && ExistFinalSymbol === 1) {
                    extractData = String(ReceiveDataArray[ReceiveDataPosition]).split(splitSymbol);
                    extractData.forEach((value, index, array) => {
                        if (value === "" || value === "--\r\n") {
                            array.splice(index, 1);
                        }
                    });
                    if (firstPos > 0) {
                        tmps = String(extractData[0]).substr(0, String(extractData[0]).length - 2);
                        if (typeof running_receive_event === "function") {
                            running_receive_event(running_FileName, String(tmps).length);
                        }
                        StreamInstance[StreamInstance.length - 1].write(tmps, 'binary');
                        extractData.shift();
                    }
                    for (let num in extractData) {
                        infoHeader = getFileInfo(extractData[num]);
                        tmps = LittleDataExtract(extractData[num]);
                        await SavePathFileNameCall(infoHeader).then((val) => {
                            getConfirmCallBackData = val;
                        }).catch(val => {
                            throw new Error(val);
                        });
                        running_FileName = getConfirmCallBackData[1];
                        if (typeof running_receive_event === "function") {
                            running_receive_event(running_FileName, String(tmps).length);
                        }
                        StreamInstance[StreamInstance.length] = currentInstance.FileStream.createWriteStream(
                            currentInstance.PathStream.join(getConfirmCallBackData[0], getConfirmCallBackData[1]), 'binary');
                        StreamInstance[StreamInstance.length - 1].write(tmps, 'binary');
                    }
                } else {
                    extractData = LargeDataExtract(ReceiveDataArray[ReceiveDataPosition], splitSymbol, FinalSplitSymbol);
                    if (typeof running_receive_event === "function") {
                        running_receive_event(running_FileName, String(extractData).length);
                    }
                    StreamInstance[StreamInstance.length - 1].write(extractData, 'binary');
                }

                /**指针移动*/
                ReceiveDataPosition++;
            });

            InterfaceRequest.on("end", () => {
                /**清除中断传输检测*/
                clearInterval(detectChange);
                let countClose = 0;
                /**循环关闭所有实例*/
                for (let num in StreamInstance) {
                    StreamInstance[num].close((cv) => {
                        if (!cv) {
                            countClose++
                        }
                    });
                }
                /**文件写入流关闭完成后延迟1秒清理流实例句柄数组*/
                let FinalComplete = setInterval(() => {
                    if (countClose === StreamInstance.length) {
                        StreamInstance.splice(0);
                        ReceiveDataArray.splice(0);
                        /**检测并执行接收完成事件*/
                        if (typeof complete_receive_event === "function") {
                            complete_receive_event();
                        }
                        clearInterval(FinalComplete);
                    }
                }, 1000);
            });
        }

        /**接收之前*/
        switch (currentInstance.DataTypeDetect(before_receive_event)) {
            case "fun":
                before_receive_event();
                DataReceive();
                break;
            case "anf":
                before_receive_event().finally(() => {
                    DataReceive();
                });
                break;
            default:
                DataReceive();
                break;
        }
    } else {
        throw new Error("未检测到有效的配置数据！");
    }
}

module.exports = {webServerFileUpdateModule, webServerDataUpdate};